package com.ttw.wallpaper;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.service.wallpaper.WallpaperService;
import android.view.SurfaceHolder;


public class LiveWallpaperService extends WallpaperService {

    @Override
    public void onCreate() {
        super.onCreate();
        
        WallpaperEngine.getInstance().init(this);
    }

    public class LiveEngine extends Engine {
        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            
            if (!isPreview()) {
                WallpaperEngine.getInstance().checkAppState(LiveWallpaperService.this);
            }
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            
            if (visible) {
                SurfaceHolder surfaceHolder = getSurfaceHolder();
                Canvas canvas = null;
                try {
                    canvas = surfaceHolder.lockCanvas();
                    Bitmap bitmap = null;
                    if (isPreview()) {
                        bitmap = WallpaperEngine.getInstance().getPreviewWallpaper();
                    } else {
                        bitmap = WallpaperEngine.getInstance().getDefaultWallpaper();
                    }
                    Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
                    Rect dest = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
                    canvas.drawBitmap(bitmap, src, dest, null);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (canvas != null) {
                            surfaceHolder.unlockCanvasAndPost(canvas);
                        }
                    } catch (Exception ignored) {
                    }
                }
            }
        }
    }

    @Override
    public Engine onCreateEngine() {

        return new LiveEngine();
    }
}
